package cloud.maque.auth.controller;

import cloud.maque.sso.client.annotations.TempToken;
import cloud.maque.sso.client.model.ThridSite;
import cloud.maque.sso.client.service.Oauth2Service;
import cloud.maque.sso.client.utils.SoMap;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {


    @Autowired
    Oauth2Service oauth2Service;


    @Autowired
    HttpSession httpSession;

    @PostMapping("/bind-user-self")
    @TempToken
    public SaResult LoginAndBind(@RequestParam("username") String username,
                                 @RequestParam("password") String password,
                                 @RequestBody ThridSite thridSite) {
        SaResult result = oauth2Service.LongAndBind(username, password, thridSite);
        if (result.getCode() == 200) {
            httpSession.setAttribute("userId", result.get("data", SoMap.class).get("uid"));
            httpSession.setAttribute("accessToken", result.get("data", SoMap.class).get("access_token"));
        }
        return result;
    }


    @GetMapping("/logout-self")
    public SaResult LogoutSelf() {
        httpSession.removeAttribute("userId");
        httpSession.removeAttribute("userName");
        httpSession.removeAttribute("accessToken");
        StpUtil.logout();
        return SaResult.ok();
    }
}
